package dao

import (
	"zg3yk/inits"
	"zg3yk/model"
)

func CreateQun(userId int) (err error) {
	tx := inits.DB.Begin()
	result := &model.Qun{
		UserId: userId,
	}
	if err = inits.DB.Create(&result).Error; err != nil {
		return err
	}
	result1 := &model.QunUser{
		UserId: userId,
		TypeId: 1,
		RoomId: int(result.ID),
	}
	if err = inits.DB.Create(&result1).Error; err != nil {
		return err
	}
	tx.Commit()
	return nil
}
func AddQunUser(userId int, roomId int, ids int) (err error) {
	var qun *model.QunUser
	inits.DB.Where("user_id=?", userId).Find(&qun)
	if qun.TypeId == 1 || qun.TypeId == 2 {
		inits.DB.Create(&model.QunUser{
			UserId: ids,
			RoomId: roomId,
		})
	} else {
		return err
	}
	return nil

}
func UpdateQunUser(userId int, roomId int, typeId int, id int) (err error) {
	var qun *model.QunUser
	inits.DB.Where("user_id=?", userId).Find(&qun)
	if qun.TypeId == 1 {
		inits.DB.Model(&qun).Update("type_id", typeId).Where("user_id=? and room_id=?", id, roomId)
	} else {
		return err
	}
	return nil

}
func DeleteQun(userId int, roomId int) (err error) {
	var qun *model.QunUser
	inits.DB.Where("user_id=?", userId).Find(&qun)
	if qun.TypeId == 1 {
		inits.DB.Where("room_id=?", roomId).Delete(&model.Qun{})
	}
	return nil
}
